#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

#define SERVER "admin.hdedu.fun"
#define PORT 443
#define PORT_STR "443"

int start_ssl() {
    SSL_CTX *ctx;
    SSL *ssl;
    BIO *bio;

    // 初始化 OpenSSL 库
    SSL_library_init();
    OpenSSL_add_all_algorithms();
    SSL_load_error_strings();

    // 创建 SSL 上下文
    ctx = SSL_CTX_new(SSLv23_client_method());
    // ctx = SSL_CTX_new(TLS_client_method());
    if (!ctx) {
        fprintf(stderr, "Error creating SSL context.\n");
        return 1;
    }

    SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);

    // 创建 SSL 对象
    ssl = SSL_new(ctx);
    if (!ssl) {
        fprintf(stderr, "Error creating SSL structure.\n");
        SSL_CTX_free(ctx);
        return 1;
    }

    // 创建一个 BIO 对象，连接到服务器
    bio = BIO_new_ssl_connect(ctx);
    BIO_set_conn_hostname(bio, SERVER ":" "https");

    // 将 SSL 对象和 BIO 对象关联
    SSL_set_bio(ssl, bio, bio);

    // 在 SSL 连接上执行握手
    if (SSL_connect(ssl) <= 0) {
        fprintf(stderr, "Error during SSL handshake.\n");
        ERR_print_errors_fp(stderr);
        SSL_free(ssl);
        SSL_CTX_free(ctx);
        return 1;
    }

    // 构造 HTTP GET 请求
    const char *request = "GET / HTTP/1.1\r\nHost: " SERVER "\r\nConnection: close\r\n\r\n";
    
    // 发送 HTTP 请求
    SSL_write(ssl, request, strlen(request));

    // 接收并打印服务器响应
    char buffer[4096];
    int bytes_received = SSL_read(ssl, buffer, sizeof(buffer) - 1);
    if (bytes_received > 0) {
        buffer[bytes_received] = '\0';
        printf("Server Response:\n%s\n", buffer);
    } else {
        fprintf(stderr, "Error receiving data from server.\n");
    }

    // 关闭 SSL 连接
    SSL_shutdown(ssl);
    SSL_free(ssl);
    SSL_CTX_free(ctx);

    return 0;
}